package com.xpf.aspect;
/**
 * 利用aop监测每个service中的方法执行的时间，超过3秒-->error，超过2秒-->warn
 */

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component //当前类对象存入spring容器中
public class ServiceLogAspect {

    public static final Logger log = LoggerFactory.getLogger(ServiceLogAspect.class);

    //环绕通知，注册切点
    @Around("execution(* com.xpf.service.impl..*.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        log.info("======== 开始执行 {}.{} =======",
                joinPoint.getTarget().getClass(),
                joinPoint.getSignature().getName());

        long begin = System.currentTimeMillis();

        //执行目标 service
        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();
        long takeTime = end - begin;
        if (takeTime > 3000){
            log.error("=======执行结束，耗时：{} 毫秒 =======", takeTime);
        }else if (takeTime > 2000){
            log.warn("=======执行结束，耗时：{} 毫秒 =======", takeTime);
        }else{
            log.info("=======执行结束，耗时：{} 毫秒 =======", takeTime);
        }

        return result;
    }

}
